package com.jingdianjichi.interview.server.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import com.jingdianjichi.interview.server.config.intercepter.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * mvc全局处理
 */
@Configuration
public class GlobalConfig extends WebMvcConfigurationSupport {

    /**
     * 自定义HTTP消息转换器列表
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //确保默认的消息转换器被保留
        super.configureMessageConverters(converters);
        converters.add(mappingJackson2HttpMessageConverter());
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**");
    }

    /**
     * 自定义mappingJackson2HttpMessageConverter  用特定的ObjectMapper配置处理JSON格式的数据
     */

    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
        //自定义配置的 ObjectMapper 来处理JSON数据的序列化和反序列化
        ObjectMapper objectMapper = new ObjectMapper();
        //禁用了当遇到没有getter方法的空Java Bean时抛出异常的行为，使得即使某些Bean为空也不会导致序列化失败
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
        // 设置了序列化时忽略值为 null 的属性，这可以减少输出的JSON大小，提高效率 不输出null的字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return new MappingJackson2HttpMessageConverter(objectMapper);
    }
}
